package org.fxd.zweixin.util;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Strings;


/**
 * base64工具
 * @author    hanjiefei
 * @date      2019-11-25
 * @version   V1.0
 * @Copyright 2019 nuoyun All rights reserved.
 */
public class FileToBase64 {
	
	public static Logger log = LoggerFactory.getLogger(FileToBase64.class);
    
   
    /**
     * 把base64转化为文件.
     *
     * @param base64   base64
     * @param filePath 目标文件路径
     * @return boolean isTrue
     */
    public static Boolean decryptByBase64(String base64, String filePath) {
        if (Strings.isNullOrEmpty(base64) && Strings.isNullOrEmpty(filePath)) {
            return Boolean.FALSE;
        }
        try {
        	Files.write(Paths.get(filePath),
        			Base64.getDecoder().decode(base64.substring(base64.indexOf(',') + 1)), StandardOpenOption.CREATE);
        } catch (IOException e) {
            log.error("",e);
        }
        return Boolean.TRUE;
    }

    /**
     * 把文件转化为base64.
     *
     * @param filePath 源文件路径
     * @return String  转化后的base64
     */
    public static String encryptToBase64(String filePath) {
        if (!Strings.isNullOrEmpty(filePath)) {
            try {
            	byte[] bytes = Files.readAllBytes(Paths.get(filePath));
                return Base64.getEncoder().encodeToString(bytes);
            } catch (IOException e) {
            	log.error("",e);
            }
        }
        return null;
    }
    
}